<template>
	<div class="vip-manage-page">
		<h1>
			VIP兑换码此时不可用，功能还有待完善，请关注
			<a href="https://gitee.com/it-heima-ht/projects" target="_blank">程序员Tao</a> 获得更多信息
		</h1>
		<div class="page-header">
			<h1>VIP 兑换码管理</h1>
			<a-button type="primary" @click="showGenerateModal">
				<PlusOutlined />
				生成兑换码
			</a-button>
		</div>

		<!-- 搜索和筛选 -->
		<div class="search-section">
			<a-form layout="inline" :model="searchForm" @finish="handleSearch">
				<a-form-item label="兑换码">
					<a-input v-model:value="searchForm.code" placeholder="请输入兑换码" style="width: 200px" />
				</a-form-item>
				<a-form-item label="状态">
					<a-select v-model:value="searchForm.status" placeholder="请选择状态" style="width: 120px">
						<a-select-option value="">全部</a-select-option>
						<a-select-option value="unused">未使用</a-select-option>
						<a-select-option value="used">已使用</a-select-option>
						<a-select-option value="expired">已过期</a-select-option>
					</a-select>
				</a-form-item>
				<a-form-item>
					<a-button type="primary" html-type="submit">搜索</a-button>
					<a-button @click="resetSearch" style="margin-left: 8px">重置</a-button>
				</a-form-item>
			</a-form>
		</div>

		<!-- 兑换码列表 -->
		<div class="table-section">
			<a-table
				:dataSource="redeemCodes"
				:columns="columns"
				:pagination="pagination"
				:loading="loading"
				@change="handleTableChange"
				rowKey="id"
			>
				<template #bodyCell="{ column, record }">
					<template v-if="column.key === 'code'">
						<a-typography-text copyable>{{ record.code }}</a-typography-text>
					</template>
					<template v-else-if="column.key === 'status'">
						<a-tag :color="getStatusColor(record.status)">
							{{ getStatusText(record.status) }}
						</a-tag>
					</template>
					<template v-else-if="column.key === 'validUntil'">
						<span>{{ formatDate(record.validUntil) }}</span>
					</template>
					<template v-else-if="column.key === 'usedAt'">
						<span>{{ record.usedAt ? formatDate(record.usedAt) : '-' }}</span>
					</template>
					<template v-else-if="column.key === 'usedBy'">
						<span>{{ record.usedBy || '-' }}</span>
					</template>
					<template v-else-if="column.key === 'actions'">
						<a-space>
							<a-button v-if="record.status === 'unused'" type="primary" size="small" @click="editCode(record)">
								编辑
							</a-button>
							<a-popconfirm
								title="确定要删除这个兑换码吗？"
								@confirm="deleteCode(record.id)"
								v-if="record.status === 'unused'"
							>
								<a-button type="primary" danger size="small">删除</a-button>
							</a-popconfirm>
						</a-space>
					</template>
				</template>
			</a-table>
		</div>

		<!-- 生成兑换码模态框 -->
		<a-modal
			v-model:open="generateModalVisible"
			title="生成VIP兑换码"
			@ok="handleGenerate"
			:confirmLoading="generateLoading"
		>
			<a-form :model="generateForm" layout="vertical">
				<a-form-item label="数量" required>
					<a-input-number v-model:value="generateForm.count" :min="1" :max="100" style="width: 100%" />
				</a-form-item>
				<a-form-item label="有效期" required>
					<a-date-picker v-model:value="generateForm.validUntil" style="width: 100%" :disabled-date="disabledDate" />
				</a-form-item>
				<a-form-item label="备注">
					<a-textarea v-model:value="generateForm.remark" :rows="3" placeholder="可选，添加备注信息" />
				</a-form-item>
			</a-form>
		</a-modal>

		<!-- 编辑兑换码模态框 -->
		<a-modal v-model:open="editModalVisible" title="编辑兑换码" @ok="handleEdit" :confirmLoading="editLoading">
			<a-form :model="editForm" layout="vertical">
				<a-form-item label="兑换码">
					<a-input v-model:value="editForm.code" disabled />
				</a-form-item>
				<a-form-item label="有效期" required>
					<a-date-picker v-model:value="editForm.validUntil" style="width: 100%" :disabled-date="disabledDate" />
				</a-form-item>
				<a-form-item label="备注">
					<a-textarea v-model:value="editForm.remark" :rows="3" />
				</a-form-item>
			</a-form>
		</a-modal>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import dayjs, { type Dayjs } from 'dayjs'

// 数据定义
const loading = ref(false)
const redeemCodes = ref<any[]>([])
const generateModalVisible = ref(false)
const editModalVisible = ref(false)
const generateLoading = ref(false)
const editLoading = ref(false)

// 搜索表单
const searchForm = reactive({
	code: '',
	status: '',
})

// 生成表单
const generateForm = reactive({
	count: 1,
	validUntil: null as Dayjs | null,
	remark: '',
})

// 编辑表单
const editForm = reactive({
	id: '',
	code: '',
	validUntil: null as Dayjs | null,
	remark: '',
})

// 分页配置
const pagination = reactive({
	current: 1,
	pageSize: 10,
	total: 0,
	showSizeChanger: true,
	showQuickJumper: true,
	showTotal: (total: number) => `共 ${total} 条数据`,
})

// 表格列配置
const columns = [
	{
		title: '兑换码',
		dataIndex: 'code',
		key: 'code',
		width: 200,
	},
	{
		title: '状态',
		dataIndex: 'status',
		key: 'status',
		width: 100,
	},
	{
		title: '有效期至',
		dataIndex: 'validUntil',
		key: 'validUntil',
		width: 150,
	},
	{
		title: '使用时间',
		dataIndex: 'usedAt',
		key: 'usedAt',
		width: 150,
	},
	{
		title: '使用用户',
		dataIndex: 'usedBy',
		key: 'usedBy',
		width: 120,
	},
	{
		title: '备注',
		dataIndex: 'remark',
		key: 'remark',
		ellipsis: true,
	},
	{
		title: '操作',
		key: 'actions',
		width: 120,
		fixed: 'right' as const,
	},
]

// 初始化加载数据
onMounted(() => {
	loadRedeemCodes()
})

// 加载兑换码数据
const loadRedeemCodes = async () => {
	loading.value = true
	try {
		// TODO: 调用后端API获取兑换码列表
		// const res = await getRedeemCodesUsingPost({
		//   current: pagination.current,
		//   pageSize: pagination.pageSize,
		//   ...searchForm
		// })

		// 模拟数据
		await new Promise((resolve) => setTimeout(resolve, 500))
		const mockData = Array.from({ length: 8 }, (_, i) => ({
			id: `code_${i + 1}`,
			code: `VIP${Date.now()}${i.toString().padStart(3, '0')}`,
			status: ['unused', 'used', 'expired'][i % 3],
			validUntil: dayjs().add(30, 'day').toDate(),
			usedAt: i % 3 === 1 ? dayjs().subtract(5, 'day').toDate() : null,
			usedBy: i % 3 === 1 ? `user_${i}` : null,
			remark: `第${i + 1}批生成的兑换码`,
			createdAt: dayjs().subtract(i, 'day').toDate(),
		}))

		redeemCodes.value = mockData
		pagination.total = 50
	} catch (error) {
		message.error('加载兑换码列表失败')
	} finally {
		loading.value = false
	}
}

// 搜索
const handleSearch = () => {
	pagination.current = 1
	loadRedeemCodes()
}

// 重置搜索
const resetSearch = () => {
	Object.assign(searchForm, { code: '', status: '' })
	pagination.current = 1
	loadRedeemCodes()
}

// 表格变化处理
const handleTableChange = (pag: any) => {
	Object.assign(pagination, pag)
	loadRedeemCodes()
}

// 显示生成模态框
const showGenerateModal = () => {
	generateForm.count = 1
	generateForm.validUntil = dayjs().add(30, 'day')
	generateForm.remark = ''
	generateModalVisible.value = true
}

// 生成兑换码
const handleGenerate = async () => {
	if (!generateForm.validUntil) {
		message.error('请选择有效期')
		return
	}

	generateLoading.value = true
	try {
		// TODO: 调用后端API生成兑换码
		// const res = await generateRedeemCodesUsingPost({
		//   count: generateForm.count,
		//   validUntil: generateForm.validUntil.toDate(),
		//   remark: generateForm.remark
		// })

		await new Promise((resolve) => setTimeout(resolve, 1000))
		message.success(`成功生成 ${generateForm.count} 个兑换码`)
		generateModalVisible.value = false
		loadRedeemCodes()
	} catch (error) {
		message.error('生成兑换码失败')
	} finally {
		generateLoading.value = false
	}
}

// 编辑兑换码
const editCode = (record: any) => {
	editForm.id = record.id
	editForm.code = record.code
	editForm.validUntil = dayjs(record.validUntil)
	editForm.remark = record.remark
	editModalVisible.value = true
}

// 处理编辑
const handleEdit = async () => {
	if (!editForm.validUntil) {
		message.error('请选择有效期')
		return
	}

	editLoading.value = true
	try {
		// TODO: 调用后端API更新兑换码
		// const res = await updateRedeemCodeUsingPost({
		//   id: editForm.id,
		//   validUntil: editForm.validUntil.toDate(),
		//   remark: editForm.remark
		// })

		await new Promise((resolve) => setTimeout(resolve, 500))
		message.success('更新成功')
		editModalVisible.value = false
		loadRedeemCodes()
	} catch (error) {
		message.error('更新失败')
	} finally {
		editLoading.value = false
	}
}

// 删除兑换码
const deleteCode = async (id: string) => {
	try {
		// TODO: 调用后端API删除兑换码
		// const res = await deleteRedeemCodeUsingPost({ id })

		await new Promise((resolve) => setTimeout(resolve, 500))
		message.success('删除成功')
		loadRedeemCodes()
	} catch (error) {
		message.error('删除失败')
	}
}

// 获取状态颜色
const getStatusColor = (status: string) => {
	const colorMap: Record<string, string> = {
		unused: 'green',
		used: 'blue',
		expired: 'red',
	}
	return colorMap[status] || 'default'
}

// 获取状态文本
const getStatusText = (status: string) => {
	const textMap: Record<string, string> = {
		unused: '未使用',
		used: '已使用',
		expired: '已过期',
	}
	return textMap[status] || status
}

// 格式化日期
const formatDate = (date: string | Date) => {
	return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 禁用过去的日期
const disabledDate = (current: Dayjs) => {
	return current && current < dayjs().startOf('day')
}
</script>

<style scoped lang="scss">
.vip-manage-page {
	.page-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24px;

		h1 {
			margin: 0;
			color: #2d3748;
		}
	}

	.search-section {
		background: white;
		padding: 24px;
		border-radius: 8px;
		margin-bottom: 24px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	}

	.table-section {
		background: white;
		padding: 24px;
		border-radius: 8px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	}

	:deep(.ant-table-thead > tr > th) {
		background: #f8fafc;
		font-weight: 600;
	}
}
</style>
